from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import SKU,SPU,Brand,Cate,SPUSpecification,SpecificationOption,SKUImage
# Create your views here.
class SPUView(APIView):
    # 获取全部数据
    def get(self,request):
        page = int(request.query_params.get('page'))
        pagesize = int(request.query_params.get('pagesize'))
        spu = SPU.objects.all()[(page - 1) * pagesize:(page * pagesize)]
        spu_list=[]
        # 序列化
        for i in spu:
            brand=Brand.objects.get(id=i.brand_id)
            spu_list.append({
                'id':i.id,
                'name':i.name,
                'brand_name': brand.name,
                'brand':brand.id,
                'category1': i.category1_id,
                'category2': i.category2_id,
                'category3': i.category3_id,
                'comment_num': i.comment_num,
                'sales': i.sales,
                'desc_detail': i.desc_detail,
                'desc_pack': i.desc_pack,
                'desc_service': i.desc_service,
            })
        return Response({
            'code': 200,
            'msg': '获取全部成功',
            'result': spu_list,
            'total': SPU.objects.all().count()
        })
    # 添加
    def post(self,request):
        # 接收数据
        name = request.data.get('name')
        brand_id = request.data.get('brand')
        category1_id = request.data.get('category1')
        category2_id = request.data.get('category2')
        category3_id = request.data.get('category3')
        desc_detail = request.data.get('desc_detail')
        desc_pack = request.data.get('desc_pack')
        desc_service = request.data.get('desc_service')
        # 频道频道组是否存在
        try:
            brand=Brand.objects.get(id=brand_id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'频道未找到'})
        try:
            # 添加数据
            SPU.objects.create(
                name = name,
                brand_id = brand.id,
                category1_id = category1_id,
                category2_id = category2_id,
                category3_id = category3_id,
                desc_detail = desc_detail,
                desc_pack = desc_pack,
                desc_service = desc_service,
            )
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'添加失败'})
        return Response({'code': 200, 'msg': '添加成功'})

class Spu(APIView):
    # 修改
    def get(self,request,id):
        spu = SPU.objects.filter(id=id)
        spu_list = []
        for i in spu:
            brand = Brand.objects.get(id=i.brand_id)
            spu_list.append({
                'id': i.id,
                'name': i.name,
                'brand_name': brand.name,
                'category1_id': i.category1_id,
                'category2_id': i.category2_id,
                'category3_id': i.category3_id,
                'comment_num': i.comment_num,
                'sales': i.sales,
                'desc_detail': i.desc_detail,
                'desc_pack': i.desc_pack,
                'desc_service': i.desc_service,
            })
        return Response(spu_list)

    def put(self, request, id):
        name=request.data.get('name')
        brand_id= request.data.get('brand_name')
        category1_id=request.data.get('category1_id')
        category2_id=request.data.get('category2_id')
        category3_id=request.data.get('category3_id')
        desc_detail= request.data.get('desc_detail')
        desc_pack= request.data.get('desc_pack')
        desc_service= request.data.get('desc_service')
        # 频道频道组是否存在
        try:
            brand = Brand.objects.get(id=brand_id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '频道未找到'})
        # print()
        try:
            spu = SPU.objects.get(id=id)
            # print(spu)
            spu.name=name
            spu.brand_id = brand.id
            spu.category1_id = category1_id
            spu.category2_id = category2_id
            spu.category3_id = category3_id
            spu.desc_detail =desc_detail
            spu.desc_pack = desc_pack
            spu.desc_service = desc_service
            spu.save()
            # spu.brand_name = brand_name
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'修改失败'})
        return Response({'code':200,'msg':'修改成功'})
    # 删除
    def delete(self,request,id):
        try:
            SPU.objects.get(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'删除失败'})
        return Response({'code': 20, 'msg': '删除成功'})
# 获取所有品牌
class Brands(APIView):
    def get(self,request):
        brand=Brand.objects.all()
        brand_list=[]
        for i in brand:
            brand_list.append({
                'id':i.id,
                'name':i.name
            })
        return Response(brand_list)
    # 获取分类信息
    def post(self,request,id):
        # cate = Cate.objects.get(id=id)
        cate_cid=Cate.objects.filter(cid_id=id)
        cate_list=[]
        for i in cate_cid:
            cate_list.append({
                'id':i.id,
                'name':i.name
            })
        # print(cate)
        # print(cate_cid)
        return Response(cate_list)

class SKUView(APIView):
    # 获取所有sku及查询单个商品信息
    def get(self,request):
        page = int(request.query_params.get('page'))
        pagesize = int(request.query_params.get('pagesize'))
        keyword = request.query_params.get('keyword')
        # 判断是否需要查询
        if keyword:
            sku=SKU.objects.filter(name=keyword)
        else:
            # 获取所有信息并分页
            sku=SKU.objects.all()[(page - 1) * pagesize:(page * pagesize)]
        sku_list=[]
        # 序列化
        if sku:
            for i in sku:
                cate=Cate.objects.get(id=i.cate_id)
                sku_list.append({
                    'id':i.id,
                    'name':i.name,
                    'describe':i.describe,
                    'price': i.price,
                    'stock': i.stock,
                    'detail': i.detail,
                    'image_default': i.image_default,
                    'is_selling': i.is_selling,
                    'sales': i.sales,
                    'cate': cate.id,
                    'cate_name':cate.name,
                    'spu': i.spu_id,
                })
            return Response({
                'code': 200,
                'msg': '获取全部成功',
                'result': sku_list,
                'total': SKU.objects.all().count()
            })
        else:
            return Response({'code':204,'msg':'获取失败'})
    # 添加SKU
    def post(self,request):
        # 获取前端数据
        name=request.data.get('name')
        spu_id=request.data.get('spu')
        cate_id=request.data.get('cate')
        describe=request.data.get('describe')
        price=request.data.get('price')
        stock=request.data.get('stock')
        is_selling=request.data.get('is_selling')
        # 判断是否上架
        print('----------->',is_selling)
        if is_selling=='true':
            is_selling=True
        else:
            is_selling=False
        try:
            # 写入数据库
            SKU.objects.create(
                name=name,
                spu_id=spu_id,
                cate_id=cate_id,
                describe=describe,
                price=price,
                stock=stock,
                is_selling=is_selling,
            )
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'添加失败'})
        return Response({'code':200,'msg':'添加成功'})

class SKUInfo(APIView):
    # 获取单个商品
    def get(self,request,id):
        try:
            sku = SKU.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'数据不存在'})

        cate = Cate.objects.get(id=sku.cate_id)
        spu=SPU.objects.get(id=sku.spu_id)
        return Response({
                'name': sku.name,
                'describe': sku.describe,
                'price': sku.price,
                'stock': sku.stock,
                'is_selling': sku.is_selling,
                'cate': cate.id,
                'cate_name': cate.name,
                'spu': spu.id,
                'spu_name': spu.name,
        })
    # 修改单个商品
    def put(self,request,id):
        name = request.data.get('name')
        spu_name = request.data.get('spu')
        cate_name = request.data.get('cate')
        describe = request.data.get('describe')
        price = request.data.get('price')
        stock = request.data.get('stock')
        is_selling = request.data.get('is_selling')
        print(type(is_selling))
        spu=SPU.objects.get(name=spu_name)
        cate = Cate.objects.get(name=cate_name)
        try:
            SKU.objects.filter(id=id).update(
                name=name,
                spu_id=spu,
                cate_id=cate,
                describe=describe,
                price=price,
                stock=stock,
                is_selling=is_selling,
            )
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'数据修改失败'})
        return Response({'code': 200, 'msg': '数据修改成功'})
    # 删除
    def delete(self,request,id):
        try:
            SKU.objects.get(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'删除失败'})
        return Response({'code': 20, 'msg': '删除成功'})

class Spus(APIView):
    # 获取所有spu
    def get(self,request):
        spu = SPU.objects.all()
        spu_list = []
        # 序列化
        for i in spu:
            spu_list.append({
                'id': i.id,
                'name': i.name,
            })
        return Response(spu_list)

class Specs(APIView):
    # 获取全部规格信息并分页
    def get(self,request):
        page = int(request.query_params.get('page'))
        pagesize = int(request.query_params.get('pagesize'))
        spec=SPUSpecification.objects.all()[(page - 1) * pagesize:(page * pagesize)]
        specs=[]
        for i in spec:
            specs.append({
                'id':i.id,
                'name':i.name,
                'spu':i.spu_id,
                'spu_name': i.spu.name,
            })
        return Response({
            'code': 200,
            'msg': '获取全部成功',
            'result': specs,
            'total': SPUSpecification.objects.all().count()
        })
    # 添加
    def post(self,request):
        name=request.data.get('name')
        spu_id=request.data.get('spu')
        try:
            SPUSpecification.objects.create(name=name,spu_id=spu_id)
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '添加失败'})
        return Response({'code': 200, 'msg': '添加成功'})

class SpecInfo(APIView):
    # 修改
    def get(self,request,id):
        try:
            spec=SPUSpecification.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '规格获取失败'})
        return Response({
            'id':spec.id,
                'name':spec.name,
                'spu':spec.spu_id,
                'spu_name': spec.spu.name,
        })
    def put(self,request,id):
        name = request.data.get('name')
        spu_id = request.data.get('spu')
        try:
            SPUSpecification.objects.filter(id=id).update(name=name,spu_id=spu_id)
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '修改规格信息失败'})
        return Response({'code': 200, 'msg': '修改规格信息成功'})
    # 删除
    def delete(self,request,id):
        try:
            SPUSpecification.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '删除规格信息失败'})
        return Response({'code': 200, 'msg': '删除规格信息成功'})

class Option(APIView):
    # 查询全部规格选项
    def get(self,request):
        page = int(request.query_params.get('page'))
        pagesize = int(request.query_params.get('pagesize'))
        option = SpecificationOption.objects.all()[(page - 1) * pagesize:(page * pagesize)]
        options = []
        for i in option:
            options.append({
                'id': i.id,
                'value': i.value,
                'spec': i.spec_id,
                'spec_name': i.spec.name,
            })
        return Response({
            'code': 200,
            'msg': '获取全部成功',
            'result': options,
            'total': SpecificationOption.objects.all().count()
        })
    # 添加规格选项
    def post(self,request):
        value=request.data.get('name')
        spec_id=request.data.get('spec_id')
        try:
            SpecificationOption.objects.create(value=value,spec_id=spec_id)
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '添加规格选项失败'})
        return Response({'code': 200, 'msg': '添加规格选项成功'})

class OptionInfo(APIView):
    # 修改
    def get(self,request,id):
        try:
            option = SpecificationOption.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '规格选项获取失败'})
        return Response({
            'name': option.value,
            'spec_id': option.spec_id,
        })
    def put(self,request,id):
        name = request.data.get('name')
        spec_id = request.data.get('spec_id')
        try:
            SpecificationOption.objects.filter(id=id).update(value=name, spec_id=spec_id)
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '修改规格选项失败'})
        return Response({'code': 200, 'msg': '修改规格选项成功'})
    # 删除
    def delete(self,request,id):
        try:
            SpecificationOption.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 204, 'msg': '删除规格选项失败'})
        return Response({'code': 200, 'msg': '删除规格选项成功'})

class Spec(APIView):
    # 获取所有规格信息
    def get(self,request):
        spec = SPUSpecification.objects.all()
        specs = []
        for i in spec:
            specs.append({
                'id': i.id,
                'name': i.name,
            })
        return Response(specs)

class Images(APIView):
    def get(self,request):
        # 获取全部商品图片
        page = int(request.query_params.get('page'))
        pagesize = int(request.query_params.get('pagesize'))
        img=SKUImage.objects.all()[(page - 1) * pagesize:(page * pagesize)]
        imgs=[]
        for i in img:
            imgs.append({
                'id':i.id,
                'sku': i.sku_id,
                'image': i.image,
            })
            print('---------->',imgs)
        return Response({
            'code': 200,
            'msg': '获取全部成功',
            'result': imgs,
            'total': SKUImage.objects.all().count()
        })
    # 添加商品图片
    def post(self,request):
        sku=request.data.get('sku')
        image=request.data.get('image')
        print(sku,image)
        try:
            SKUImage.objects.create(
                sku_id=sku,
                image=image
            )
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'添加失败'})
        return Response({'code': 200, 'msg': '添加成功'})

class ImageInfo(APIView):
    # 修改商品图片
    def get(self,request,id):
        try:
            img = SKUImage.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'获取图片信息失败'})
        return Response({
            'sku':img.sku_id,
            'sku_name':img.sku.name,
            'image':img.image,
        })
    def put(self,request,id):
        sku = request.data.get('sku')
        image = request.data.get('image')
        try:
            SKUImage.objects.filter(id=id).update(
                sku_id=sku,
                image=image
            )
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'修改图片信息失败'})
        return Response({'code': 204, 'msg': '修改图片信息成功'})
    # 删除
    def delete(self,request,id):
        try:
            SKUImage.objects.get(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'删除图片信息失败'})
        return Response({'code': 204, 'msg': '删除图片信息成功'})


from qiniu import Auth, put_file, etag
access_key = '_laoL-LQHXAHTmWtqpc9tiJqkSSWVjwOa2FMOnKO'
secret_key = 'wVXOkJw4UwG71Z0Buj3fiY87zfJIl7mCORDJHHgW'
class QiNiuFiles(APIView):
    def get(self,request):
        """生成上传的token"""
        q = Auth(access_key, secret_key)
        # 生成token 可以指定过期时间等
        bucket_name = 'w-m-y'
        token=q.upload_token(bucket_name)
        return Response({'msg':'OK','code':200,'qn_token':token})

class Skus(APIView):
    def get(self,request):
        sku=SKU.objects.all()
        skus=[]
        for i in sku:
            skus.append({
                'id':i.id,
                'name': i.name,
            })
        return Response(skus)





